package com.egoo.ticket.server.fallback;

import com.alibaba.fastjson.JSON;
import com.egoo.ticket.server.utils.common.DbResponse;
import com.egoo.ticket.server.utils.common.ResponseConstant;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @Author: Donny_dong
 * @Description: fallback机制，处理zuul转发异常
 * @Param: 
 * @return: 
 * @Date: 2021/1/14
 */
@Component
@Log4j2
public class MyFallBack implements FallbackProvider {
	@Override
	public String getRoute() {
		return "*";
	}

	@Override
	public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
		log.info("转发报错的服务为："+route);
		log.info("异常信息为："+cause.getMessage()+"\n"+"异常："+cause);
		return new ClientHttpResponse() {
			@Override
			public HttpStatus getStatusCode() throws IOException {
				return HttpStatus.OK;
			}

			@Override
			public int getRawStatusCode() throws IOException {
				return ResponseConstant.RES_SUCCESS_CODE;
			}

			@Override
			public String getStatusText() throws IOException {
				return HttpStatus.OK.getReasonPhrase();
			}

			@Override
			public void close() {

			}

			@Override
			public InputStream getBody() throws IOException {
				DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE,"服务繁忙，请稍后重试");
				return new ByteArrayInputStream(JSON.toJSONString(dbResponse).getBytes("UTF-8"));
			}

			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers = new HttpHeaders();
				headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.defaultCharset()));
				return headers;
			}
		};
	}
}
